// Copyright 2023 The MPFlutter Authors. All rights reserved.
// Use of this source code is governed by a Apache License Version 2.0 that can be
// found in the LICENSE file.

const { FlutterHostView } = require("./flutter");
const { wxSystemInfo } = require("./system_info");

export class Main {
  constructor(canvas) {
    this.canvas = canvas;
    this.canvas.requestAnimationFrame = (cb) => {
      requestAnimationFrame(cb);
      return 0.0;
    };
    this.addEventListeners();
  }

  async fixAndroidGLParams(canvas) {
    if (wxSystemInfo.platform !== "android") return;
    const ctxGetter = canvas.getContext;
    canvas.getContext = function (type, v) {
      const ctx = ctxGetter(type, v);
      const originGetParameter = ctx.getParameter.bind(ctx);
      ctx.getParameter = function (v) {
        const value = originGetParameter(v);
        if (v === 7938) {
          return "WebGL 1.0 (OpenGL ES 2.0 Chromium)";
        } else if (v === 35724) {
          return "WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)";
        }
        return value;
      };
      return ctx;
    };
  }

  async run() {
  
    this.canvas.width = this.canvas.width * wxSystemInfo.pixelRatio;
    this.canvas.height = this.canvas.height * wxSystemInfo.pixelRatio;
    aaaa(this.canvas);

    await new Promise((resolve) => {
      // 微信小程序 getSystemInfoAsync 接口在 PC 上是存在 BUG 的
      // https://developers.weixin.qq.com/community/develop/doc/000e46e65dc4e0be8a305ecb161c00?highLine=getsysteminfoasync%2520fail
      const res = wx.getSystemInfoSync();
      Object.assign(wxSystemInfo, res);
      resolve();
    });
    this.fixAndroidGLParams(this.canvas);
    require("./mpjs");
    await Promise.all([loadAssetPages(), loadCanvasKitPages(), loadPlugins()]);
    FlutterHostView.shared.self = this;
    getApp()._flutter.window.requestAnimationFrame = this.canvas.requestAnimationFrame;
    getApp()._flutter.activeCanvas = this.canvas;

    wx.onKeyboardHeightChange((detail) => {
      FlutterHostView.shared.onkeyboardheightchange({ detail });
    });
    
  }

  setData() { }

  addEventListeners() {
    wx.onTouchStart(this.ontouchstart.bind(this));
    wx.onTouchMove(this.ontouchmove.bind(this));
    wx.onTouchEnd(this.ontouchend.bind(this));
    wx.onTouchCancel(this.ontouchcancel.bind(this));
    wx.onShow(() => {
      FlutterHostView.shared.onShow?.();
    });
  }

  ontouchstart() {
    FlutterHostView.shared.touching = true;
    callFlutterTouchEvent("ontouchstart", arguments);
  }

  ontouchmove() {
    callFlutterTouchEvent("ontouchmove", arguments);
  }

  ontouchend() {
    FlutterHostView.shared.touching = false;
    callFlutterTouchEvent("ontouchend", arguments);
  }

  ontouchcancel() {
    FlutterHostView.shared.touching = false;
    callFlutterTouchEvent("ontouchcancel", arguments);
  }
}

function loadAssetPages() {
  return new Promise((resolve) => {
    wx.loadSubpackage({
      name: "assets",
      success: function () {
        resolve();
      },
      fail: function () {
        resolve();
      },
    });
  });
}

function loadCanvasKitPages() {
  return new Promise((resolve) => {
    wx.loadSubpackage({
      name: "canvaskit",
      success: function () {
        resolve();
      },
      fail: function () {
        resolve();
      },
    });
  });
}

async function loadPlugins() {
  await Promise.all([
    new Promise((resolve) => { wx.loadSubpackage({ name: "audioplayers_web", success: function () { require("../../audioplayers_web/pages/main", resolve); }, fail: function () { require("../../audioplayers_web/pages/main", resolve); }, }); }),
    new Promise((resolve) => { wx.loadSubpackage({ name: "mpflutter_wechat_socket", success: function () { require("../../mpflutter_wechat_socket/pages/main", resolve); }, fail: function () { require("../../mpflutter_wechat_socket/pages/main", resolve); }, }); }),
  ])

}

function setupFlutterApp(canvas) {
  return new Promise((resolve) => {
    getApp()._flutter.loader.loadEntrypoint({
      onEntrypointLoaded: function (engineInitializer) {
        engineInitializer
          .initializeEngine()
          .then(function (appRunner) {
            appRunner.runApp();
            resolve();
            setTimeout(() => {
              FlutterHostView.shared.onwebglcontextlost?.();
              FlutterHostView.shared.onwebglcontextrestored?.();
            }, 10);
          })
          .catch(function (e) {
            console.error(e);
          });
      },
    });
  });
}

function callFlutterTouchEvent(eventName, args) {
  if (FlutterHostView.shared[eventName]) {
    FlutterHostView.shared[eventName].apply(null, [
      FlutterHostView.transformTouchEvent(args[0]),
    ]);
  }
}

// 判断版本号
function compareVersion(v1, v2) {
  v1 = v1.split(".");
  v2 = v2.split(".");
  const len = Math.max(v1.length, v2.length);
  while (v1.length < len) {
    v1.push("0");
  }
  while (v2.length < len) {
    v2.push("0");
  }
  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i]);
    const num2 = parseInt(v2[i]);
    if (num1 > num2) {
      return 1;
    }
    if (num1 < num2) {
      return -1;
    }
  }
  return 0;
}
function aaaa(canvas) {
  // 当基础库版本>=2.1.0才能使用分包能力，当不支持分包功能时，会下载完整包，因此不需要展示加载封面
  if (compareVersion(wx.getSystemInfoSync().SDKVersion, '2.1.0') > -1) {
    try {
      GameGlobal.LoadingManager = requirePlugin('MinigameLoading', {
        customEnv: {
          wx,
          canvas: canvas, // 传入主屏canvas
        }
      }).default
      // 创建封面

      GameGlobal.LoadingManager.create({
        // 填写图片模板
        images: [
          {
            src: "images/startup.png",
          }
        ],
        // 接入封面插件前主屏contexttype
        contextType: 'webgl',
        // 接入封面插件前，getContext时，传入的contextAttributes
        contextAttributes: {
          antialias: false,
          preserveDrawingBuffer: false,
          antialiasSamples: 2,
          alpha: false
        },
        showLoading: true,
        scaleMode: 1,
        designWidth: 750,
        designHeight: 1334,
        useMainCanvas: true

      }).then(() => {
        // 封面已显示
        console.log("封面已显示")

        wx.loadSubpackage({
          complete: function (complete) {
            // 分包加载失败通过 fail 回调
            console.log("分包加载完成通过 complete 回调")
          },
          fail: function (res) {
            // 分包加载失败通过 fail 回调
            console.log("分包加载失败通过 fail 回调")
          },
          name: 'pkg0',
          success: function (res) {
            // 分包加载成功后通过 success 回调
            console.log("分包加载成功后通过 success 回调")
            if (GameGlobal.LoadingManager) {

              setupFlutterApp(canvas);
              setTimeout(() => {

                GameGlobal.LoadingManager.destroy().then(() => {
                  // 销毁完成
                  console.log("销毁完成 LoadingManager 回调")
                })
              }, 500);
         
            }
          },
        })
        

      }).catch((err) => {
        // 封面创建异常
        console.log("封面创建异常", err)
      })
    } catch (error) {
      // 当前客户端不支持使用插件，会黑屏（占比小于1%）
      console.error('当前环境不支持使用插件', error);
    }
    // 支持插件，开始下载必要分包
    console.log("支持插件，开始下载必要分包")
  } else {
    console.log("不支持分包，省略分包下载，开始执行游戏逻辑")
    // 不支持分包，省略分包下载，开始执行游戏逻辑
    // 具体可见分包文档-老版本兼容： https://developers.weixin.qq.com/minigame/dev/guide/base-ability/subPackage/useSubPackage.html
  }
}




